if exists(param.R)
    echo >"0:/sys/user/actions/NetworkMode.g" "M552 I0 S1 ; Enable Ethernet mode"
    M99
    abort


; Step 1: Detect current network mode before making changes
var previousMode = "AP"                     ; Default to AP if no connection exists
var previousIP = "192.168.0.1"              ; Default AP IP

if network.interfaces[0].actualIP != "0.0.0.0"
  set var.previousIP = network.interfaces[0].actualIP
  if network.interfaces[0].actualIP == "192.168.1.50"
    set var.previousMode = "ETPC"           ; Ethernet to PC mode
  else
    set var.previousMode = "ETH"            ; Regular Ethernet mode
elif network.interfaces[1].actualIP != "0.0.0.0"
  set var.previousIP = network.interfaces[1].actualIP
  if network.interfaces[1].actualIP == "192.168.0.1"
    set var.previousMode = "AP"             ; WiFi Access Point mode
  else
    set var.previousMode = "CLIENT"         ; WiFi Client mode

M98 P"0:/sys/user/variables/APName.g"

M291 R"Ethernet Mode" P"Choose Ethernet configuration:" S4 K{"DHCP (Automatic)","Static IP (Manual)","Ethernet to PC Mode","Cancel"} F0

if input == 3
    abort "Script canceled by user"

; Store user's choice for IP configuration mode
var useStaticIP = false
var isPCMode = false

if input == 1 || input == 2
    set var.useStaticIP = true
if input == 2
    set var.isPCMode = true

; Default values for static IP
var ip = "192.168.1.100"
var subnet = "255.255.255.0"
var gateway = "192.168.1.1"

; If Ethernet to PC Mode selected, use PC-specific defaults
if var.isPCMode
    set var.ip = "192.168.1.50"
    set var.subnet = "255.255.255.0"
    set var.gateway = "192.168.1.1"

; If user chose static IP or PC mode, prompt for values (with appropriate defaults)
if var.useStaticIP
    if var.isPCMode
        ; PC Mode - show instructions and allow customization
        var pcMsg1 = "Ethernet to PC Mode Setup<br>"
        var pcMsg2 = "Default settings for direct PC connection:<br>"
        var pcMsg3 = "IP: 192.168.1.50 | Subnet: 255.255.255.0<br>"
        var pcMsg4 = "You can use defaults or customize below."
        M291 R"PC Mode Configuration" P{var.pcMsg1 ^ var.pcMsg2 ^ var.pcMsg3 ^ var.pcMsg4} S4 K{"Use Default Settings","Use Custom IP Values","Cancel"} F0
        
        if input == 2
            abort "Script canceled by user"
        
        ; If user wants custom values (input == 1), prompt for them
        if input == 1
            M291 S7 F{var.ip} R"Network Setup" P"Enter Static IP Address or use default" H15
            set var.ip = input
            
            M291 S7 F{var.subnet} R"Network Setup" P"Enter Subnet Mask or use default (enter 0 to skip)" H15
            set var.subnet = input
            
            M291 S7 F{var.gateway} R"Network Setup" P"Enter Gateway or use default (enter 0 to skip)" H15
            set var.gateway = input
    else
        ; Regular static IP mode - always prompt
        M291 S7 F{var.ip} R"Network Setup" P"Enter Static IP Address" H15
        set var.ip = input
        
        M291 S7 F{var.subnet} R"Network Setup" P"Enter Subnet Mask (enter 0 to skip)" H15
        set var.subnet = input
        
        M291 S7 F{var.gateway} R"Network Setup" P"Enter Gateway (enter 0 to skip)" H15
        set var.gateway = input
    
    ; Validate inputs
    if var.ip == ""
        M291 S1 R"Error" P{"Invalid IP address. IP cannot be empty."} T0
        abort "Invalid network settings"
    
    ; Create temp network configuration file
    echo >"0:/sys/temp-network.g" "; Network configuration"
    if var.subnet != "0"
        echo >>"0:/sys/temp-network.g" "M553 P" ^ var.subnet
    if var.gateway != "0"
        echo >>"0:/sys/temp-network.g" "M554 P" ^ var.gateway
    echo >>"0:/sys/temp-network.g" "M552 P" ^ var.ip ^ " I0 S1"

var connectionMsg = var.isPCMode ? "Connect printer to PC via Ethernet cable<br>Static IP: " ^ var.ip : "Connect to network via Ethernet cable" ^ (var.useStaticIP ? "<br>Static IP: " ^ var.ip : "<br>DHCP (Automatic)")

; User chose "Change & Test Now" (input == 0)
var instructMsg1 = "You will lose connection momentarily.<br>"
var instructMsg2 = var.isPCMode ? "Make sure Ethernet cable is connected between printer and computer.<br>" : "Make sure Ethernet cable is connected.<br>"
var instructMsg3 = "🟡 YELLOW - Testing<br>🟢 GREEN - Success<br>🔴 RED - Failed"
M291 R"Switching to Ethernet Mode" P{var.instructMsg1 ^ var.instructMsg2 ^ var.instructMsg3} S4 K{"Ethernet cable is connected","Cancel"} F0

if input == 1
    ; Clean up temp file if it exists
    if var.useStaticIP
        M471 P"0:/sys/temp-network.g"
    abort "Script canceled by user"

M98 P"0:/sys/led/pause.g"                   ; Yellow LED - testing

; Turn off both interfaces first
M552 I1 S-1                                 ; Turn off WiFi completely
M552 I0 S0                                  ; Turn off Ethernet
G4 S2

; Enable Ethernet with DHCP or Static IP
if var.useStaticIP
    M98 P"0:/sys/temp-network.g"           ; Apply static IP configuration
else
    ; Clear any previous static IP settings before enabling DHCP
    M553 P0.0.0.0                           ; Clear subnet mask
    M554 P0.0.0.0                           ; Clear gateway
    M552 I0 S1                              ; Enable Ethernet mode with DHCP
G4 S5

; Wait for Ethernet to get IP (not 0.0.0.0 or AP IP)
var expectedIP = var.useStaticIP ? var.ip : ""
while (network.interfaces[0].actualIP == "0.0.0.0" || network.interfaces[0].actualIP == "192.168.0.1") && iterations < 30
    G4 S1                                   ; Wait 1 second per iteration (max 30 seconds)

; Check if connection was successful
var connectionSuccess = false
if var.useStaticIP
    set var.connectionSuccess = network.interfaces[0].actualIP == var.ip
else
    set var.connectionSuccess = network.interfaces[0].actualIP != "0.0.0.0" && network.interfaces[0].actualIP != "192.168.0.1"

if var.connectionSuccess
    ; Success - Ethernet connected
    M98 P"0:/sys/led/end.g"                 ; Green LED for success - keep it on
    
    ; Show success message with options
    var ethIP = network.interfaces[0].actualIP
    var localName = global.APName ^ ".local"
    var successMsg1 = "✅ Ethernet Mode Connected Successfully!<br><br>"
    var modeLabel = var.isPCMode ? " (PC Mode)" : (var.useStaticIP ? " (Static)" : " (DHCP)")
    var successMsg2 = "IP Address: " ^ var.ethIP ^ var.modeLabel ^ "<br>"
    var successMsg3 = "Local Domain: " ^ var.localName ^ "<br><br>"
    var successMsg4 = "Would you like to save this mode?"
    M291 S4 R"Connection Successful" P{var.successMsg1 ^ var.successMsg2 ^ var.successMsg3 ^ var.successMsg4} K{"Save Mode","Revert to Previous","Cancel"} F0
    
    if input == 0
        ; User chose "Save Mode" - save configuration
        if var.useStaticIP
            echo >"0:/sys/user/actions/NetworkMode.g" "; Network configuration"
            if var.subnet != "0"
                echo >>"0:/sys/user/actions/NetworkMode.g" "M553 P" ^ var.subnet
            if var.gateway != "0"
                echo >>"0:/sys/user/actions/NetworkMode.g" "M554 P" ^ var.gateway
            echo >>"0:/sys/user/actions/NetworkMode.g" "M552 P" ^ var.ip ^ " I0 S1"
            M291 S1 R"Mode Saved" P{"Ethernet mode with static IP " ^ var.ip ^ " has been saved and will remain active after restart."} T0
        else
            echo >"0:/sys/user/actions/NetworkMode.g" "M552 I0 S1 ; Enable Ethernet mode"
            M291 S1 R"Mode Saved" P"Ethernet mode (DHCP) has been saved and will remain active after restart." T0
        M98 P"0:/sys/led/resetstatus.g"     ; Reset LEDs to white
        if var.useStaticIP
            M471 P"0:/sys/temp-network.g"  ; Clean up temp file
        M99
    elif input == 1
        ; User chose "Revert to Previous" - restore previous mode
        M98 P"0:/sys/led/resetstatus.g"     ; Reset LEDs to white immediately
        
        ; Turn off Ethernet
        M552 I0 S0
        G4 S2
        
        ; Restore previous mode
        if var.previousMode == "ETH"
            M552 I0 S1                      ; Enable Ethernet
        elif var.previousMode == "CLIENT"
            M552 I1 S0                      ; Set WiFi to idle
            G4 S5
            M552 I1 S1                      ; Enable as client
        elif var.previousMode == "AP"
            M552 I1 S0                      ; Set WiFi to idle
            G4 S5
            M552 I1 S2                      ; Enable as access point
        elif var.previousMode == "ETPC"
            M552 P192.168.1.50 I0 S1
            M553 P255.255.255.0
            M554 P192.168.1.1
        else
            M552 I1 S0                      ; Set WiFi to idle
            G4 S5
            M552 I1 S2                      ; Enable as access point (default)
        
        G4 S5
        
        ; Wait for previous mode to reconnect and get IP
        var waitCount = 0
        while var.waitCount < 30
            if var.previousMode == "ETH" || var.previousMode == "ETPC"
                if network.interfaces[0].actualIP != "0.0.0.0"
                    break
            else
                if network.interfaces[1].actualIP != "0.0.0.0"
                    break
            G4 S1
            set var.waitCount = var.waitCount + 1
        
        ; Get the restored IP address
        var restoredIP = var.previousMode == "ETH" || var.previousMode == "ETPC" ? network.interfaces[0].actualIP : network.interfaces[1].actualIP
        
        M291 S1 R"Reverted to Previous Mode" P{"Successfully restored previous mode.<br>IP Address: " ^ var.restoredIP} T0
        if var.useStaticIP
            M471 P"0:/sys/temp-network.g"  ; Clean up temp file
        M99
    else
        ; User chose "Cancel" - stay in new mode but don't save
        M98 P"0:/sys/led/resetstatus.g"     ; Reset LEDs to white
        if var.useStaticIP
            M471 P"0:/sys/temp-network.g"  ; Clean up temp file
        M99

; Failed - restore previous network mode
M98 P"0:/sys/led/fault.g"                   ; Red LED for failed connection

; Turn off both interfaces first (universal)
M552 I1 S-1                                 ; Turn off WiFi completely
M552 I0 S0                                  ; Turn off Ethernet
G4 S2

; Restore previous mode - only mode-specific enable commands
if var.previousMode == "ETH"
    M552 I0 S1                              ; Enable Ethernet
elif var.previousMode == "CLIENT"
    M552 I1 S0                              ; Set WiFi to idle
    G4 S5
    M552 I1 S1                              ; Enable as client
elif var.previousMode == "AP"
    M552 I1 S0                              ; Set WiFi to idle
    G4 S5
    M552 I1 S2                              ; Enable as access point
elif var.previousMode == "ETPC"
    M552 P192.168.1.50 I0 S1
    M553 P255.255.255.0
    M554 P192.168.1.1
else
    M552 I1 S0                              ; Set WiFi to idle
    G4 S5
    M552 I1 S2                              ; Enable as access point (default)

G4 S5

; Wait for previous mode to reconnect and get active IP
var waitCount = 0
while var.waitCount < 30
    if var.previousMode == "ETH" || var.previousMode == "ETPC"
        if network.interfaces[0].actualIP != "0.0.0.0"
            break
    else
        if network.interfaces[1].actualIP != "0.0.0.0"
            break
    G4 S1
    set var.waitCount = var.waitCount + 1

; Get the restored IP address
var restoredIP = var.previousMode == "ETH" || var.previousMode == "ETPC" ? network.interfaces[0].actualIP : network.interfaces[1].actualIP
if var.restoredIP == "0.0.0.0"
    set var.restoredIP = var.previousIP     ; Fallback to stored IP if reconnection failed

M291 S2 R"Connection Failed" P{"❌ Ethernet connection failed.<br><br>Automatically reverted to previous mode.<br>IP Address: " ^ var.restoredIP}

M98 P"0:/sys/led/resetstatus.g"             ; Reset LEDs to normal
if var.useStaticIP
    M471 P"0:/sys/temp-network.g"          ; Clean up temp file